package com.icode.web.controller.house;

import com.icode.core.dto.house.HomePageDTO;
import com.icode.core.shared.HomeAboutHandle;
import com.icode.service.house.HomePageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-3-2
 * Time: 下午2:47
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(value = "/home")
public class HomePageController {

    @Autowired
    private HomePageService homePageService;

    @RequestMapping(value = "show", method = RequestMethod.GET)
    public ModelAndView show() {
        HomePageDTO homePageDTO = homePageService.findHomePage();
        if (homePageDTO == null) {
            return new ModelAndView("/back/home", "homePageDTO", new HomePageDTO());
        }
        return new ModelAndView("/back/home", "homePageDTO", homePageDTO);
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(@ModelAttribute(value = "homePageDTO") @Valid HomePageDTO homePageDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "back/home";
        }
        homePageService.updateHomePage(homePageDTO);
        return "redirect:/home/show";
    }

    @RequestMapping(value = "delImg/{imgGuid}/{type}")
    public void deleteHomePageImage(@PathVariable String imgGuid, @PathVariable String type, HttpServletResponse response) {
        HomeAboutHandle.delHomePageImg(type, imgGuid, homePageService);
        homePageService.updateHomeImagesByType(type, response);
    }


}
